package com.liurong.netty.v2.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class ChatServerHandler extends SimpleChannelInboundHandler<String> {
	private static final ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

	// 第一种方式：自己存储信道。必须final修饰不然信道不能保留
	// private static final List<Channel> channelGroup = new
	// ArrayList<Channel>();

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		Channel channel = ctx.channel();
		System.out.println("聊天室：" + channel.remoteAddress() + " 在线！");
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		Channel channel = ctx.channel();
		System.out.println("聊天室：" + channel.remoteAddress() + " 离线！");
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		Channel upcoming = ctx.channel();
		upcoming.writeAndFlush(upcoming.remoteAddress() + "欢迎来来到聊天室！" + "\r\n");
		for (Channel channel : channelGroup) {
			channel.writeAndFlush(channel.remoteAddress() + " 上线了！" + "\r\n");
		}
		channelGroup.add(upcoming);
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		Channel upcoming = ctx.channel();
		System.out.println(upcoming.remoteAddress() + "下线了！");
		for (Channel channel : channelGroup) {
			channel.writeAndFlush(channel.remoteAddress() + " 下线了！" + "\r\n");
		}
		channelGroup.remove(upcoming);
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		Channel upcoming = ctx.channel();
		if (msg.equals("heartbeat")) {
			System.out.println(upcoming.remoteAddress() + msg);
			upcoming.writeAndFlush("收到你的心跳包！" + "\r\n");
		} else {
			for (Channel channel : channelGroup) {
				if (channel != upcoming) {
					channel.writeAndFlush(upcoming.remoteAddress() + "说：" + msg);
				} else {
					channel.writeAndFlush("你说：" + msg);
				}
			}
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		Channel upcoming = ctx.channel();
		System.out.println("聊天室：" + upcoming.remoteAddress() + " 异常！");
		channelGroup.remove(upcoming);
		ctx.close().sync();
	}
}
